const NeedLogin = require('../need_login.js');
const fs = require('fs');
const path = require('path');
child_process = require('child_process');

module.exports = class extends NeedLogin {
  async indexAction() {
    var db = this.mongoose('mongo/sn_upload'); // 链接数据库
    var data = this.post(); // 获取post参数
    if (this.file('files') instanceof Array) { // 判断文件字段有多个文件
      console.log('多文件')
      var url = []; // 创建url数组用于存放  最终链接
      for(var i = 0; i < this.file('files').length; i++) { // 循环文件数组
        think.mkdir(path.join(
          think.ROOT_PATH, 'www', 'upload',
          think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2)
        )) // 创建文件夹
        var path1 = path.join(
          'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
          think.uuid('v1') + path.extname(this.file('files')[i].path)
        )
        var newpath = path.join(think.ROOT_PATH, 'www', path1)
        fs.renameSync(this.file('files')[i].path, newpath)
        let filedb = new db({path: newpath,url: path1}); //创建数据库文档
        var result = await filedb.save();
        url.push(result._id)
      }
      this.json({
        url: url
      })
    } else {
      think.mkdir(path.join(
        think.ROOT_PATH, 'www', 'upload',
        think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2)
      ))// 创建文件夹
      var path1 = path.join(
        'upload' ,think.datetime(new Date()).substr(0,4),think.datetime(new Date()).substr(5,2),think.datetime(new Date()).substr(8,2),
        think.uuid('v1') + path.extname(this.file('files').path)
      )
      var newpath = path.join(think.ROOT_PATH, 'www', path1)
      fs.renameSync(this.file('files').path, newpath)
      let filedb = new db({path: newpath,url: path1}); //创建数据库文档
      var result = await filedb.save();
      this.json({
        url: result._id
      })
    }
  }
};
